package com.example.md5web;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {
    private EditText search,result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        search= (EditText) findViewById(R.id.ed_enter);
        result= (EditText) findViewById(R.id.ed_result);
    }

    public void onSearch(View view) {
        String trim = search.getText().toString().trim();
        String md5 = messageDigest("md5", trim);
        result.setText(md5);


    }

    private String messageDigest(String type, String data) {
        try {
            MessageDigest instance = MessageDigest.getInstance(type);
            instance.update(data.getBytes());
            byte[] digest = instance.digest();


            StringBuilder builder=new StringBuilder();
            for (int i = 0; i < digest.length; i++) {
                int num = digest[i] & 0xFF;

                if(num<=0xF){
                    builder.append(0);
                }
                String str = Integer.toHexString(num);
                builder.append(str);

            }

            return builder.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
